package win.zxshuo.www.service;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
import win.zxshuo.www.model.BookModel;
import win.zxshuo.www.model.TargetUrlModel;
import win.zxshuo.www.repository.TargetUrlRepository;

import java.util.Date;
import java.util.Optional;

@Service
@Configurable
public class TargetUrlService {

    @Autowired
    TargetUrlRepository targetUrlRepository;

    public TargetUrlModel addNew(BookModel bookModel,String url){
        Integer status = 1 ;
        if (hasActiveTargetUrl(bookModel.getId())){
            status = 0;
        }
        TargetUrlModel tmp = getByUrlAndBookid(bookModel,url);
        if (tmp != null){
            return tmp;
        }
        TargetUrlModel targetUrlModel = new TargetUrlModel();
        targetUrlModel.setBookModel(bookModel);
        targetUrlModel.setUrl(url);
        targetUrlModel.setCreateDate(new Date());
        targetUrlModel.setModifyDate(new Date());
        targetUrlModel.setStatus(status);
        targetUrlModel.setFailedPeriodTimes(0);
        targetUrlRepository.save(targetUrlModel);
        return targetUrlModel;
    }

    public Boolean hasActiveTargetUrl(Long bookid){
        TargetUrlModel targetUrlModel = targetUrlRepository.findActiveTargetUrl(bookid);
        return targetUrlModel != null;

    }

    public TargetUrlModel getByUrlAndBookid(BookModel bookModel,String url){
        return targetUrlRepository.findByBookModelAndUrl(bookModel,url);
    }



}
